package com.cyk.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSON;
import com.cyk.model.TokenInfo;
import com.cyk.model.WeChatUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@RestController
@Slf4j
@CrossOrigin
public class WechatController {

    @RequestMapping("/connect_test")
    public String wechatConnectTest(
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "timestamp") String timestamp,
            @RequestParam(value = "nonce") String nonce,
            @RequestParam(value = "echostr") String echostr
    ) {
        log.info("收到微信校验请求: {}", echostr);
        //TODO: 校验是否是微信请求
        return echostr;
    }

    private static final String APP_ID = "wxb00194802e8318e8";
    private static final String SECRET = "afe9fbf7282e1e3467814a926c3756ea";
    private WeChatUser weChatUser;

    @RequestMapping("/wxLogin")
    public void login(HttpServletResponse response) throws IOException {
        //redirectUrl 就是回调地址，注意要转成 UrlEncode
        String redirectUrl = URLEncoder.encode("http://8e71f2e.r2.cpolar.top/wxCallback", "UTF-8");


        //构造二维码连接地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APP_ID+
                "&redirect_uri="+redirectUrl+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        //生成二维码，扫描后跳转到上面的连接
        response.setContentType("image/png");
        QrCodeUtil.generate(url, 300, 300, "jpg", response.getOutputStream());
    }

    @RequestMapping(value = "/wxCallback")
    public String pcCallback(
            String code,
            String state,
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession session
    ) throws IOException {
        weChatUser = getUserInfo(code);
        //TODO 缓存用户信息，构造 session
        return JSON.toJSONString(weChatUser);
    }

    private WeChatUser getUserInfo(String code) throws IOException {
        //构造 http 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String tokenUrl ="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APP_ID+"&SECRET="+SECRET+"&code="+code+"&grant_type=authorization_code";
        //发请求
        HttpGet httpGet = new HttpGet(tokenUrl);
        String responseResult = "";
        //接收返回的数据
        HttpResponse response = httpClient.execute(httpGet);
        if(response.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        log.info("获取 accessToken 返回结果：{}", responseResult);
        //将结果封装到 TokenInfo 对象中
        TokenInfo tokenInfo = JSON.parseObject(responseResult, TokenInfo.class);
        //用 accessToken 获取的个人信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+tokenInfo.getAccess_token() +
                "&openid=" + tokenInfo.getOpenid() + "&lang=zh_CN";
        //构造 http 请求客户端
        HttpGet httpGet1 = new HttpGet(userInfoUrl);
        //接收响应
        HttpResponse response1 = httpClient.execute(httpGet1);
        if(response1.getStatusLine().getStatusCode() == 200) {
            responseResult = EntityUtils.toString(response1.getEntity(), "UTF-8");
        }
        log.info("获取个人信息: {}", responseResult);

        WeChatUser weChatUser = JSON.parseObject(responseResult, WeChatUser.class);
        return weChatUser;
    }



}
